<template>
    <button @click="openDefault" class="button golden">
        <div style="font-size: 20px;"> 历史资源查找及下载</div>
    </button>
    <NModal v-model:show="showDownload" title="无水印资源付费及下载" preset="card" :mask-closable="false" :bordered="false"
        style="width: 400px; height: 300px">
        <div style="display: inline-flex; justify-content: space-around; width: 100%">
            <div style="display: flex; flex-direction: column; align-items: center; justify-content: space-between">
                <NForm label-placement="left">
                    <NFormItem label="资源名称：" style="height: 35px">{{ props.toolName }}</NFormItem>
                    <NFormItem label="资源编号：" style="height: 35px">
                        <n-input v-model:value="thisTaskId" placeholder="输入资源编号查找资源" :allow-input="check"
                            :loading="taskIsQuery" :maxlength="8" />
                    </NFormItem>
                    <NFormItem label="剩余下载次数：" style="height: 35px">
                        <span style="color: red">{{ downTimes }} 次</span>
                    </NFormItem>
                    <NFormItem label="请选择文件格式：" v-if="props.toolId == 27">
                        <n-radio-group v-model:value="downSuffix" size="medium">
                            <n-radio-button key="excel" value="excel" :disabled="!docType.excel">excel</n-radio-button>
                            <n-radio-button key="word" value="word" :disabled="!docType.word">word</n-radio-button>
                        </n-radio-group>
                    </NFormItem>
                </NForm>
                <div style="display: inline-flex; justify-content: flex-end">
                    <n-button type="info" @click="down" style="margin-right: 10px"
                        :disabled="downTimes == '-' || (downTimes as number) <= 0" :loading="downloading">下载</n-button>
                    <n-button type="error" @click="close">取消</n-button>
                </div>
            </div>
        </div>
    </NModal>
</template>
<script lang="ts" setup>
import "@/assets/button.scss";
import { createDiscreteApi } from "naive-ui";
import type { IDocType } from "~/composables/imgApi";
const { dialog } = createDiscreteApi(["dialog"]);
const { message } = createDiscreteApi(["message"]);
const props = defineProps({
    toolId: {// 根据不同的工具，展示不同的下载界面
        type: Number,
        default: 0,
    },
    toolName: {
        type: String,
        required: true,
    },
});
const showDownload = ref(false); //是否显示下载弹窗
const thisTaskId = ref(""); // input框绑定的taskid，用于查询下载地址和生成二维码链接

// 默认的打开方式
function openDefault() {
    showDownload.value = true;
}

function close() {
    showDownload.value = false;
}

// 检查输入taskiD的字符是否合法
function check(value: string) {
    return !value || /^[A-Z0-9]+$/.test(value);
}

const taskIsQuery = ref(false); // 表达输入的task已经在向后台查询，防止重复查询
const downTimes = ref<number | string>("-"); // 下载次数
function getDownTimes() {
    taskIsQuery.value = true;
    if (props.toolId == 27) {
        get27DownType();// 27号工具需要选择文件类型,再查询下载次数
    }
    getDownTimesApi(thisTaskId.value, props.toolId).then((res) => {
        if (res.code < 0) {
            message.error((res.data as string) + "。如有疑问请联系管理员，日志id：" + res.logId);
            downTimes.value = "-" as string; // 获取下载次数失败，显示-。
        } else {
            downTimes.value = res.data as number; // 获取下载次数
        }
        taskIsQuery.value = false;
    });

}
const downloading = ref(false); // 是否正在下载
// 下载文件
function down() {
    downloading.value = true;
    if (props.toolId != 27) {
        imgDown(thisTaskId.value, props.toolId).then((res) => {
            const { message } = createDiscreteApi(["message"]);
            if (res.code < 0) {
                message.error(("资源" + thisTaskId.value + "下载失败：" + (res as IResponse<string>).data) as string, { duration: 8000 });
            } else {
                message.success("资源" + thisTaskId.value + res.data, { duration: 5000 });
                close()
                downTimes.value = res.downTimes as number; // 获取下载次数并更新到页面上。
            }
            downloading.value = false;
        });
    } else {
        // 27号工具的下载逻辑
        down27();
    }
}

const downSuffix = ref("word"); // 27h号需要的参数，下载文件的后缀名，word或excel
// 根据taskID查询下载地址
function down27() {
    img2docDownUrl(thisTaskId.value, downSuffix.value, props.toolId).then((res) => {
        if (res.code < 0) {
            dialog.error({
                title: "下载资源失败！",
                content: res.data + "。如有疑问请联系管理员，日志id：" + res.logId,
                positiveText: "确定",
                onPositiveClick: () => { },
            });
        } else {
            const dom = document.createElement("a");
            dom.href = res.data as string;
            dom.style.display = "none";
            document.body.appendChild(dom);
            dom.click();
            document.body.removeChild(dom);
            close()
            downTimes.value = Number(res.headers.get("down-times"))
        }
        
        downloading.value = false;
    });
}

let docType = ref({ word: false, excel: false } as IDocType); // 27号需要选择文件类型
function get27DownType() {
    img2docResult(thisTaskId.value, props.toolId).then((res) => {
        if (res.code < 0) {
            message.error(res.data + "。如有疑问请联系管理员，日志id：" + res.logId);
        } else {
            docType.value = res.data as IDocType;
        }
    });
}
// 监听taskId的变化，当taskId发生变化时且长度等于8时，调用img2docResult方法获取最新的下载地址。
watch(thisTaskId, (newVal) => {
    if (newVal && newVal.length == 8) {
        downTimes.value = "-"; // 重置下载次数为-
        if (props.toolId == 27) {
            docType.value.excel = false;
            docType.value.word = false;
            downSuffix.value = "word";
        }
        getDownTimes(); // 获取下载次数
    } else {
        downTimes.value = "-"; // 重置下载次数为-
        // 重置
        if (props.toolId == 27) {
            docType.value.excel = false;
            docType.value.word = false;
            downSuffix.value = "word";
        }
    }
});
</script>
<style>
.cardRefresh:hover {
    /* 改变鼠标样式 */
    cursor: pointer;
    /* 鼠标悬停时显示为手型 */
}

.backdropFilter {
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    backdrop-filter: blur(6px);
    background-color: rgba(0, 0, 0, 0.5);
    /* 半透明黑色 */
    z-index: 100;
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    /* 确保遮罩层在所有其他元素之上 */
}

.payButton {
    font-size: 40px;
    height: 60px;
    width: 320px;
    border-radius: 30px;
    margin-bottom: 10px;
}

.golden {
    filter: hue-rotate(200deg);
}

.golden:hover {
    filter: hue-rotate(200deg) saturate(1.5);
}

.golden:active {
    filter: hue-rotate(200deg) saturate(1.7);
}
</style>
